package addbatch;

import tools.HikariDataSourceUtils;
import tools.Order;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class OrderAddBatchDao {

    public void batchSave(List<Order> orders) {
        long time = System.currentTimeMillis();
        Timestamp createTime = new Timestamp(time);
        String sql = " insert into biz_order( user_id, status, create_time, total_cost, item_amount) values(?,?,?,?,? )";
        try (Connection dbConnection = HikariDataSourceUtils.getConnection();
             PreparedStatement preparedStatement = dbConnection.prepareStatement(sql)){
            for (Order order : orders) {
                //be careful! parameterIndex is beginning with 1;
                preparedStatement.setInt(1, order.getUserId());
                preparedStatement.setShort(2, order.getStatus());
                preparedStatement.setTimestamp(3, createTime);
                preparedStatement.setDouble(4, order.getTotalCost());
                preparedStatement.setInt(5, order.getItemAmount());
                preparedStatement.addBatch();
            }
            int[] ints = preparedStatement.executeBatch();
            System.out.println("batchSave success, done "+ IntStream.of(ints).sum());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        List<Order> orders = new ArrayList<>(1000);
        for(int i=0;i<5000;i++){
            Order o = new Order();
            o.setUserId(1);
            o.setStatus((short)0);
            o.setTotalCost(0.0);
            o.setItemAmount(0);
            orders.add(o);
        }
        OrderAddBatchDao orderAddBatchDao = new OrderAddBatchDao();
        for(int i=0;i<200;i++){
            orderAddBatchDao.batchSave(orders);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("run "+ (endTime-time)/1000.0+" s");


        //每次1000笔，执行1000次
        //batchSave success, done 1000
        //run 588.422 s

        //每次5000笔，执行200次
        //batchSave success, done 5000
        //run 586.729 s
    }
}
